package mapred.filters.bloom;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.bloom.BloomFilter;
import org.apache.hadoop.util.bloom.Key;
import org.apache.hadoop.util.hash.Hash;

import java.io.File;
import java.io.IOException;

public class MRBloomFilter {

    public static class BloomFilterMapper extends Mapper<Object, Text, Text, NullWritable> {

        BloomFilter bloomFilter = new BloomFilter(10, 2, Hash.MURMUR_HASH);

        //建立预定义集合
        protected void setup(Context context) {
            try {
                // 需要往布隆过滤器中提前加入过滤用的元素（key)
                // 需要往布隆过滤器中添加Bloom的Key类型的对象
                // Key对象构造函数接收的值是比特数组
                // 字符串类型默认具有getBytes（）函数来实现字符串到比特数组的转换

                // 下述代码实现动态获取布隆过滤器的元素
//                String filter="a,b,c,d,e,f";
//                filter=context.getConfiguration().get("bloomFilter");
//                String[] filters = filter.split(",");
//                for (String f: filters){
//                    bloomFilter.add(new Key(f.getBytes()));
//                }
                bloomFilter.add(new Key("Beijing".getBytes()));
                bloomFilter.add(new Key("Shanghai".getBytes()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String word = value.toString();
            //判断值是否在预判的集合中，用到了已经编译过的布隆过滤器对象的membershipTest方法
            if (bloomFilter.membershipTest(new Key(word.getBytes()))) {
                context.write(value, NullWritable.get());
            }
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        if (args.length != 2) {
            System.err.println(
                    "!!!!!!!!!!!!!! Usage!!!!!!!!!!!!!!: \nhadoop jar <jar-name> "
                            + "mapred.filters.bloom.MRBloomFilter "
                            + "<input-path> "
                            + "<output-path>");
            System.exit(1);
        }
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "BloomFilter");
        //与自己定义的类名保持一致
        job.setJarByClass(MRBloomFilter.class);

        //与自己定义的Mapper类和Reducer类保持一致
        // 在一个Job中如果不设置Reducer的类，那么默认执行Reducer父类中的reduce方法
        job.setMapperClass(BloomFilterMapper.class);
        //设置的输出键和输出值和mapper定义的需要保持一致。
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);
        job.setNumReduceTasks(1);
        //输入输出路径
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileUtil.fullyDelete(new File(args[1]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);

    }
}
